﻿

using Microsoft.Maui;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics.Platform;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;

namespace DisplayReadingClient
{
    public partial class MainPage : ContentPage
    {
        /// <summary>
        /// 
        /// </summary>
        TcpClient tcpClient { get; set; }
        /// <summary>
        /// 是否初始化
        /// </summary>
        private bool isIni { get; set; }

        /// <summary>
        /// 配置
        /// </summary>
        public ComData config { get; set; }
        /// <summary>
        /// 为每一个切片创建一个UDP套接字
        /// </summary>
        UdpClient[] udpServer;

        int tcpport = 10001;

        // 开启数据接收线程
        Microsoft.Maui.Graphics.IImage[] bitmaps = null;
        picview view { get; set; }
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += MainPage_Loaded;
            view = new picview();
            can.Drawable = view;
        }

        private void MainPage_Loaded(object? sender, EventArgs e)
        {
            tcpClient = new TcpClient();
           // Task.Factory.StartNew(Heart);
            //Task.Factory.StartNew(Receive);
        }
        void OnSwiped(object sender, SwipedEventArgs e)
        {
            switch (e.Direction)
            {
                case SwipeDirection.Left:
                    // Handle the swipe
                    break;
                case SwipeDirection.Right:
                    // Handle the swipe
                    break;
                case SwipeDirection.Up:
                    // Handle the swipe
                    break;
                case SwipeDirection.Down:
                    Navigation.PushAsync(new SetPage());
                    // Handle the swipe
                    break;
            }
        }
        private void Heart()
        {
            while (true)
            {
                if (tcpClient.Connected)
                {
                    ComData comData = new ComData()
                    {
                        com = EnumCom.ini,
                    };
                    if (isIni)
                    {
                        comData.com = EnumCom.heart;
                    }
                    var senddata = JsonHelp.ToString(comData);
                    var databyte = UTF8Encoding.UTF8.GetBytes(senddata);
                    tcpClient.Client.Send(databyte);
                }
                else
                {
                    tcpClient.Connect(IPAddress.Parse("127.0.0.1"), tcpport);
                }
                Thread.Sleep(1000);
            }
        }
        private void Receive()
        {
            while (true)
            {
                if (tcpClient.Connected)
                {
                    var data = tcpClient.GetStream();
                    byte[] bytes = new byte[1024];
                    data.Read(bytes, 0, bytes.Length);
                    var dstdata = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    var dst = JsonHelp.ToObj<ComData>(dstdata);
                    if (dst.com == EnumCom.ini)
                    {
                        config = dst;
                        isIni = true;
                        SetUi2();

                        Task.Factory.StartNew(IniSocket);
                    }
                    Console.WriteLine(dstdata);
                }
                Thread.Sleep(200);
            }
        }
        private void SetUi2()
        {
            bitmaps = new Microsoft.Maui.Graphics.IImage[config.dataCount];
        }

        private void IniSocket()
        {
            udpServer = new UdpClient[config.dataCount];
            for (int i = 0; i < config.dataCount; i++)
            {
                int port = tcpport + i + 1;
                IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), config.startPort + i);
                // 创建套接字
                udpServer[i] = new UdpClient(endpoint);
            }

            while (true)
            {
                Parallel.For(0, udpServer.Length, i =>
                {
                    if (udpServer[i].Available > 0)
                    {
                        EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        //IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), reveiveport);
                        // 设置一个64k的字节数组作为缓存
                        byte[] data = new byte[65536];
                        var dst = udpServer[i].Client.ReceiveFrom(data, ref remoteEndPoint);
                        //string receivedData = Encoding.UTF8.GetString(data);
                        //Console.WriteLine($"接收端口:{((System.Net.IPEndPoint)remoteEndPoint).Port}+ {receivedData}");

                        MemoryStream ms = new MemoryStream(data, 0, data.Length);
                        var image = PlatformImage.FromStream(ms);
                        bitmaps[i] = image;
                    }
                });

                SetImage2(bitmaps);
                GC.Collect();

                Thread.Sleep(20);
            }
        }

        private void SetImage2(Microsoft.Maui.Graphics.IImage[] bitmaps)
        {
            view.bitmaps = bitmaps;
            MainThread.BeginInvokeOnMainThread(() =>
            {
                can.Invalidate();
            });
        }
    }

}
